import time
from sqlmodel import Session, select, func

from app.exception.base import AppException, HttpResp
from app.models.system_log_login import SystemLogLogin, SystemLogLoginListIn, SystemLogLoginListOut
from app.models.system_log_operate import SystemLogOperate, SystemLogOperateListIn, SystemLogOperateListOut


class SystemLogService:
    def __init__(self, session: Session):
        self.session = session

    async def login(self, list_in: SystemLogLoginListIn) -> SystemLogLoginListIn:
        name = list_in.name
        is_stop = list_in.isStop
        page_no = list_in.page_no
        page_size = list_in.page_size

        where = [SystemLogLogin.delete_time.is_(None)]
        if name:
            where.append(SystemLogLogin.name.like('%{0}%'.format(name)))
        if is_stop is not None:
            where.append(SystemLogLogin.is_stop == is_stop)

        count_statement = (
            select(func.count())
            .select_from(SystemLogLogin)
            .where(*where)
        )
        count = self.session.exec(count_statement).one()
        offset = (page_no - 1) * page_size
        statement = (
            select(SystemLogLogin).where(*where).offset(offset).limit(page_size)
        )
        items = self.session.exec(statement).all()
        return SystemLogLoginListOut(data=items, count=count)

    async def operate(self, list_in: SystemLogOperateListIn) -> SystemLogOperateListIn:
        name = list_in.name
        is_stop = list_in.isStop
        page_no = list_in.page_no
        page_size = list_in.page_size

        where = [SystemLogOperate.delete_time.is_(None)]
        if name:
            where.append(SystemLogOperate.name.like('%{0}%'.format(name)))
        if is_stop is not None:
            where.append(SystemLogOperate.is_stop == is_stop)

        count_statement = (
            select(func.count())
            .select_from(SystemLogOperate)
            .where(*where)
        )
        count = self.session.exec(count_statement).one()
        offset = (page_no - 1) * page_size
        statement = (
            select(SystemLogOperate).where(*where).offset(offset).limit(page_size)
        )
        items = self.session.exec(statement).all()
        return SystemLogOperateListOut(data=items, count=count)
